package com.astar.controller.login;


import com.astar.entity.CustomUser;
import com.astar.mapper.UserMapper;
import com.astar.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {

    @Autowired
    private IUserService userServiceImpl;

    @RequestMapping("/toLogin")
    public Object toLogin(){
        return "login";
    }

    @RequestMapping("/logout")
    public Object toLogout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }

    @RequestMapping("/toIndex")
    public Object toIndex() {
        return "index";
    }



    @RequestMapping("/submitLogin")

    public Object submitLogin(String username, String password, ModelMap modelMap, HttpServletRequest request){

        /**
         *使用shiro编写登录认证
         */
        //1.获取subject
        Subject subject = SecurityUtils.getSubject();
        //2.封装账号密码
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username,password);
        HttpSession session = request.getSession();
        //3.执行登录
        try {
            subject.login(usernamePasswordToken);
            List<CustomUser> customUser = userServiceImpl.selectUserPower(username);
            session.setAttribute("menus",customUser);
            return "redirect:/toIndex";
        } catch (UnknownAccountException e) {

            modelMap.put("msg","用户名不存在");
            e.printStackTrace();
        } catch (IncorrectCredentialsException e) {

            modelMap.put("msg","密码不正确");
            e.printStackTrace();
        } catch (LockedAccountException e){
            modelMap.put("msg","账户被锁定");
        }

        return "login";
    }
}
